<template>
  <div class="question-page">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="question-card">
          <el-skeleton :loading="loading" animated>
            <template #default>
              <div class="question-header">
                <h1 class="title">{{ question?.title || '示例问题标题' }}</h1>
                <div class="meta">
                  <span class="views">{{ formatNumber(question?.views || 0) }} 浏览</span>
                  <span class="answers">{{ answers.length }} 回答</span>
                </div>
              </div>
              
              <div class="question-content" v-if="question?.content">
                {{ question.content }}
              </div>
              
              <div class="question-tags" v-if="question?.tags?.length">
                <el-tag
                  v-for="tag in question.tags"
                  :key="tag"
                  size="small"
                  class="tag"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </template>
          </el-skeleton>
        </el-card>

        <div class="answer-section">
          <div class="answer-header">
            <h3>{{ answers.length }} 个回答</h3>
            <el-select v-model="sortBy" size="small">
              <el-option label="默认排序" value="default" />
              <el-option label="最新回答" value="newest" />
              <el-option label="最多赞同" value="votes" />
            </el-select>
          </div>

          <div class="write-answer" v-if="isLoggedIn">
            <div class="editor-header">
              <h3>写回答</h3>
              <div class="editor-tips">
                <el-alert
                  title="回答注意事项"
                  type="info"
                  :closable="false"
                  show-icon
                >
                  <template #default>
                    <p>1. 请确保回答对他人有帮助</p>
                    <p>2. 尊重原创，避免简单复制</p>
                    <p>3. 理性讨论，友善交流</p>
                  </template>
                </el-alert>
              </div>
            </div>
            <el-input
              v-model="newAnswer"
              type="textarea"
              :rows="8"
              placeholder="写下你的回答..."
              class="answer-editor"
            />
            <div class="answer-actions">
              <el-checkbox v-model="isAnonymous">匿名回答</el-checkbox>
              <div class="action-buttons">
                <el-button @click="clearAnswer">清空</el-button>
                <el-button type="primary" @click="submitAnswer" :loading="submitting">
                  发布回答
                </el-button>
              </div>
            </div>
          </div>
          
          <el-card v-for="(answer, index) in sortedAnswers" :key="index" class="answer-card">
            <div class="answer-author">
              <el-avatar :size="40" :src="answer.author.avatar" />
              <div class="author-info">
                <div class="name">{{ answer.author.name }}</div>
                <div class="bio">{{ answer.author.bio }}</div>
              </div>
            </div>
            
            <div class="answer-content">
              {{ answer.content }}
            </div>
            
            <div class="answer-footer">
              <div class="votes">
                <el-button type="text" @click="voteAnswer(index, 'up')">
                  <el-icon><CaretTop /></el-icon>
                  {{ answer.upvotes }}
                </el-button>
                <el-button type="text" @click="voteAnswer(index, 'down')">
                  <el-icon><CaretBottom /></el-icon>
                </el-button>
              </div>
              
              <div class="actions">
                <el-button type="text" @click="showCommentInput(index)">
                  <el-icon><ChatLineRound /></el-icon>
                  评论 {{ answer.comments.length }}
                </el-button>
                <el-button type="text">
                  <el-icon><Share /></el-icon>
                  分享
                </el-button>
                <el-button type="text">
                  <el-icon><Star /></el-icon>
                  收藏
                </el-button>
              </div>
            </div>

            <!-- 评论区域 -->
            <div class="comments-section" v-if="answer.showComments">
              <div class="comment-input">
                <el-input
                  v-model="answer.newComment"
                  type="textarea"
                  :rows="2"
                  placeholder="写下你的评论..."
                />
                <div class="comment-actions">
                  <el-button type="primary" size="small" @click="submitComment(index)">
                    发表评论
                  </el-button>
                </div>
              </div>
              
              <div class="comment-list">
                <div v-for="(comment, commentIndex) in answer.comments" :key="commentIndex" class="comment-item">
                  <div class="comment-author">
                    <el-avatar :size="24" :src="comment.author.avatar" />
                    <span class="name">{{ comment.author.name }}</span>
                  </div>
                  <div class="comment-content">{{ comment.content }}</div>
                  <div class="comment-meta">
                    <span class="time">{{ comment.time }}</span>
                    <el-button type="text" size="small" @click="replyComment(index, commentIndex)">
                      回复
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
      
      <el-col :span="8">
        <el-card class="related-questions">
          <template #header>
            <div class="card-header">
              <span>相关问题</span>
            </div>
          </template>
          <ul class="question-list">
            <li v-for="q in relatedQuestions" :key="q.id">
              <router-link :to="'/question/' + q.id">
                {{ q.title }}
              </router-link>
              <span class="answer-count">{{ q.answerCount }}个回答</span>
            </li>
          </ul>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { useQuestionStore } from '@/stores/question'
import { useUserStore } from '@/stores/user'
import { CaretTop, CaretBottom, ChatLineRound, Share, Star } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { marked } from 'marked'
import DOMPurify from 'dompurify'

const route = useRoute()
const questionStore = useQuestionStore()
const userStore = useUserStore()

const loading = ref(true)
const question = ref({
  title: 'OpenSourceSoftmareNews',
  content: '此聚合汇聚了一些开源软件消息',
  tags: ['开源软件', '消息聚合'],
  views: 1234
})
const answers = ref([
  {
    author: {
      name: '双黄蛋',
      avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      bio: '前端开发工程师'
    },
    content: '介绍  \n\n\n\n特点\n\n高性能(单机可支持几十万至百万人同时在线)\n轻量、可扩展性极强\n支持集群多机部署\n支持SSL/TLS加密传输\n消息格式极其简洁(JSON)\n一端口支持可插拔多种协议(Socket自定义IM协议、Websocket、Http),各协议可分别独立部署。\n内置消息持久化(离线、离史、漫游)，保证消息可靠性，高性能存储\n各种丰富的API接口。\n零成本部署，一键启动。',
    upvotes: 42,
    comments: [
      {
        author: {
          name: '皇帝',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        },
        content: '这个回答很有帮助！',
        time: '2小时前'
      }
    ],
    showComments: false,
    newComment: ''
  },
  {
    author: {
      name: '酒心菩提',
      avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      bio: '后端开发工程师'
    },
    content: 'CIM是一套完善的消息推送框架，可应用于信令推送，即时聊天，移动设备指令推送等领域。开发者可沉浸于业务开发，不用关心消息通道长连接、消息编解码协议等繁杂处理。CIM采用业内主流开源技术构建，易于扩展和使用，并完美支持集群部署支持海量链接，目前支持websocket，android，ios，桌面应用，系统应用等多端接入持,可应用于移动应用，物联网，智能家居，嵌入式开发，桌面应用，WEB应用即时消服务。',
    upvotes: 28,
    comments: [],
    showComments: false,
    newComment: ''
  }
])
const relatedQuestions = ref([
  {
    id: 1,
    title: '相关问题1',
    answerCount: 5
  },
  {
    id: 2,
    title: '相关问题2',
    answerCount: 3
  }
])
const sortBy = ref('default')
const newAnswer = ref('')
const isAnonymous = ref(false)
const submitting = ref(false)

const isLoggedIn = computed(() => userStore.isLoggedIn)

const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num
}

const sortedAnswers = computed(() => {
  const sorted = [...answers.value]
  switch (sortBy.value) {
    case 'newest':
      return sorted.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    case 'votes':
      return sorted.sort((a, b) => b.upvotes - a.upvotes)
    default:
      return sorted
  }
})

const clearAnswer = () => {
  newAnswer.value = ''
  isAnonymous.value = false
}

const submitAnswer = async () => {
  if (!newAnswer.value.trim()) {
    ElMessage.warning('请输入回答内容')
    return
  }
  
  submitting.value = true
  try {
    // 模拟添加新回答
    answers.value.unshift({
      author: {
        name: isAnonymous.value ? '匿名用户' : '当前用户',
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        bio: '普通用户'
      },
      content: newAnswer.value,
      upvotes: 0,
      comments: [],
      showComments: false,
      newComment: ''
    })
    
    ElMessage.success('回答发布成功')
    clearAnswer()
  } catch (error) {
    console.error('Failed to submit answer:', error)
    ElMessage.error('发布回答失败')
  } finally {
    submitting.value = false
  }
}

const voteAnswer = (index, type) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }
  
  if (type === 'up') {
    answers.value[index].upvotes++
    ElMessage.success('已赞同')
  } else {
    ElMessage.success('已反对')
  }
}

const showCommentInput = (index) => {
  answers.value[index].showComments = !answers.value[index].showComments
}

const submitComment = (answerIndex) => {
  const answer = answers.value[answerIndex]
  if (!answer.newComment.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  answer.comments.push({
    author: {
      name: '当前用户',
      avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
    },
    content: answer.newComment,
    time: '刚刚'
  })

  answer.newComment = ''
  ElMessage.success('评论发布成功')
}

const replyComment = (answerIndex, commentIndex) => {
  const comment = answers.value[answerIndex].comments[commentIndex]
  answers.value[answerIndex].newComment = `@${comment.author.name} `
}

onMounted(() => {
  loading.value = false
})
</script>

<style scoped lang="scss">
.question-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;

  .question-card {
    margin-bottom: 20px;

    .question-header {
      margin-bottom: 20px;

      .title {
        font-size: 24px;
        font-weight: 600;
        color: #121212;
        margin-bottom: 10px;
      }

      .meta {
        color: #8590a6;
        font-size: 14px;

        span {
          margin-right: 15px;
        }
      }
    }

    .question-content {
      font-size: 15px;
      line-height: 1.7;
      color: #121212;
      margin-bottom: 20px;
    }

    .question-tags {
      .tag {
        margin-right: 8px;
      }
    }
  }

  .answer-section {
    .answer-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        margin: 0;
        font-weight: 600;
      }
    }

    .write-answer {
      margin-bottom: 30px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(18, 18, 18, 0.1);
      padding: 20px;

      .editor-header {
        margin-bottom: 20px;

        h3 {
          margin: 0 0 15px;
          font-size: 18px;
          font-weight: 600;
          color: #121212;
        }

        .editor-tips {
          margin-bottom: 20px;
        }
      }

      .answer-editor {
        margin-bottom: 20px;
      }

      .answer-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #f0f0f0;

        .action-buttons {
          .el-button {
            margin-left: 10px;
          }
        }
      }
    }

    .answer-card {
      margin-bottom: 20px;

      .answer-author {
        display: flex;
        align-items: center;
        margin-bottom: 15px;

        .author-info {
          margin-left: 10px;

          .name {
            font-weight: 600;
            color: #121212;
          }

          .bio {
            font-size: 14px;
            color: #8590a6;
          }
        }
      }

      .answer-content {
        font-size: 15px;
        line-height: 1.7;
        color: #121212;
        margin-bottom: 20px;
      }

      .answer-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid #f0f0f0;
        padding-top: 10px;

        .votes {
          display: flex;
          align-items: center;

          .el-button {
            margin-right: 10px;
          }
        }

        .actions {
          .el-button {
            margin-left: 15px;

            .el-icon {
              margin-right: 4px;
            }
          }
        }
      }

      .comments-section {
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid #f0f0f0;

        .comment-input {
          margin-bottom: 20px;

          .comment-actions {
            margin-top: 10px;
            text-align: right;
          }
        }

        .comment-list {
          .comment-item {
            padding: 10px 0;
            border-bottom: 1px solid #f0f0f0;

            &:last-child {
              border-bottom: none;
            }

            .comment-author {
              display: flex;
              align-items: center;
              margin-bottom: 5px;

              .name {
                margin-left: 8px;
                font-weight: 500;
                color: #121212;
              }
            }

            .comment-content {
              font-size: 14px;
              color: #121212;
              margin-bottom: 5px;
            }

            .comment-meta {
              display: flex;
              justify-content: space-between;
              align-items: center;
              font-size: 12px;
              color: #8590a6;
            }
          }
        }
      }
    }
  }

  .related-questions {
    position: sticky;
    top: 20px;

    .question-list {
      list-style: none;
      padding: 0;
      margin: 0;

      li {
        padding: 10px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        a {
          color: #175199;
          text-decoration: none;
          font-size: 14px;

          &:hover {
            color: #1e80ff;
          }
        }

        .answer-count {
          font-size: 12px;
          color: #8590a6;
          margin-left: 8px;
        }
      }
    }
  }
}

.markdown-body {
  font-size: 14px;
  line-height: 1.6;
  color: #121212;

  h1, h2, h3, h4, h5, h6 {
    margin-top: 24px;
    margin-bottom: 16px;
    font-weight: 600;
    line-height: 1.25;
  }

  p {
    margin-top: 0;
    margin-bottom: 16px;
  }

  code {
    padding: 0.2em 0.4em;
    margin: 0;
    font-size: 85%;
    background-color: rgba(27, 31, 35, 0.05);
    border-radius: 3px;
  }

  pre {
    padding: 16px;
    overflow: auto;
    font-size: 85%;
    line-height: 1.45;
    background-color: #f6f8fa;
    border-radius: 3px;
  }

  img {
    max-width: 100%;
    box-sizing: border-box;
  }

  a {
    color: #0366d6;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}
</style> 